- Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path135. Candy.c
59 lines (40 loc) · 1.15 KB
/
135. Candy.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
135. Candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
*/
intcandy(int*ratings, intratingsSize) {
int*candies;
inti, x;
if (ratingsSize<2) returnratingsSize;
candies=malloc(ratingsSize*sizeof(int));
//assert(candies);
candies[0] =1;
for (i=1; i<ratingsSize; i++) {
if (ratings[i] >ratings[i-1]) {
candies[i] =candies[i-1] +1;
} else {
candies[i] =1;
}
}
x=candies[ratingsSize-1];
for (i=ratingsSize-2; i >= 0; i--) {
if (ratings[i] >ratings[i+1]) {
if (candies[i] <= candies[i+1]) {
candies[i] =candies[i+1] +1;
}
}
x+=candies[i];
}
free(candies);
returnx;
}
/*
Difficulty:Hard
Total Accepted:70.3K
Total Submissions:284.7K
Related Topics Greedy
*/